import {
  asyncRoutes,
  constantRoutes,
  resetRouter
} from '@/router'

import router from '@/router'
// import Router from 'vue-router'

function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = {
      ...route
    }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: [],
  roles: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_ROUTESDATA: (state, routes) => {
    state.roles = routes
  }
}

const actions = {
  generateRoutes({
    commit, state
  }, roles) {
    return new Promise(resolve => {
      const accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      resetRouter()
      commit('SET_ROUTES', accessedRoutes)
      commit('SET_ROUTESDATA', roles)
      router.addRoutes(accessedRoutes)
      // router.options.routes = state.routes
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
